package com.icoolkj.ms.pay.controller;

import com.icoolkj.ms.common.core.response.ServerResponseEntity;
import com.icoolkj.ms.pay.constant.PayConstant;
import com.icoolkj.ms.api.pay.model.PayOrder;
import com.icoolkj.ms.pay.service.PayService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("/pay")
@RequiredArgsConstructor
@Tag(name = "支付接口", description = "支付相关接口")
public class PayOrderController {

    @Qualifier("wechatPayService")
    private final PayService wechatPayService;

    @Qualifier("alipayService")
    private final PayService alipayService;
    
    private final RestTemplate restTemplate;

    @PostMapping("/create/wechat")
    @Operation(summary = "创建微信支付订单")
    public ServerResponseEntity<Map<String, String>> createWechatOrder(@RequestBody PayOrder payOrder) {
        try {
            Map<String, String> result = wechatPayService.createOrder(payOrder);
            return ServerResponseEntity.success(result);
        } catch (Exception e) {
            log.error("创建微信支付订单失败", e);
            return ServerResponseEntity.fail("创建微信支付订单失败: " + e.getMessage());
        }
    }

    @PostMapping("/create/alipay")
    @Operation(summary = "创建支付宝支付订单")
    public ServerResponseEntity<Map<String, String>> createAlipayOrder(@RequestBody PayOrder payOrder) {
        try {
            Map<String, String> result = alipayService.createOrder(payOrder);
            return ServerResponseEntity.success(result);
        } catch (Exception e) {
            log.error("创建支付宝支付订单失败", e);
            return ServerResponseEntity.fail("创建支付宝支付订单失败: " + e.getMessage());
        }
    }

    @PostMapping("/notify/wechat")
    @Operation(summary = "微信支付回调")
    public ServerResponseEntity<String> handleWechatNotify(@RequestBody String notifyData) {
        try {
            // 解析通知数据
            Map<String, String> params = parseWechatNotifyData(notifyData);
            
            // 先让支付服务进行验签和基础处理
            boolean success = wechatPayService.handlePayNotify("WECHAT", params);
            if (!success) {
                return ServerResponseEntity.success(PayConstant.WechatPay.FAIL);
            }
            
            // 根据业务类型进行不同的业务处理
            String businessType = getBusinessTypeFromParams(params);
            
            // 针对会员充值业务，调用会员充值回调处理
            if (PayConstant.BusinessType.MEMBER_RECHARGE.equals(businessType)) {
                // 实际项目中应使用服务间调用，这里简化示例
                callMemberRechargeCallback("WECHAT", params);
            } else if (PayConstant.BusinessType.GOODS_PURCHASE.equals(businessType)) {
                // 调用商品购买回调处理
                // TODO: 商品购买业务处理
            }
            
            return ServerResponseEntity.success(PayConstant.WechatPay.SUCCESS);
        } catch (Exception e) {
            log.error("处理微信支付回调失败", e);
            return ServerResponseEntity.success(PayConstant.WechatPay.FAIL);
        }
    }

    @PostMapping("/notify/alipay")
    @Operation(summary = "支付宝支付回调")
    public ServerResponseEntity<String> handleAlipayNotify(@RequestParam Map<String, String> params) {
        try {
            // 先让支付服务进行验签和基础处理
            boolean success = alipayService.handlePayNotify("ALIPAY", params);
            if (!success) {
                return ServerResponseEntity.success(PayConstant.AliPay.FAIL);
            }
            
            // 根据业务类型进行不同的业务处理
            String businessType = getBusinessTypeFromParams(params);
            
            // 针对会员充值业务，调用会员充值回调处理
            if (PayConstant.BusinessType.MEMBER_RECHARGE.equals(businessType)) {
                // 实际项目中应使用服务间调用，这里简化示例
                callMemberRechargeCallback("ALIPAY", params);
            } else if (PayConstant.BusinessType.GOODS_PURCHASE.equals(businessType)) {
                // 调用商品购买回调处理
                // TODO: 商品购买业务处理
            }
            
            return ServerResponseEntity.success(PayConstant.AliPay.SUCCESS);
        } catch (Exception e) {
            log.error("处理支付宝支付回调失败", e);
            return ServerResponseEntity.fail(PayConstant.AliPay.FAIL);
        }
    }

    @GetMapping("/query/{orderNo}")
    @Operation(summary = "查询支付订单")
    public ServerResponseEntity<PayOrder> queryOrder(@PathVariable String orderNo, @RequestParam String payType) {
        try {
            PayService payService = "WECHAT".equals(payType) ? wechatPayService : alipayService;
            PayOrder payOrder = payService.queryOrder(orderNo);
            return ServerResponseEntity.success(payOrder);
        } catch (Exception e) {
            log.error("查询支付订单失败", e);
            return ServerResponseEntity.fail("查询支付订单失败: " + e.getMessage());
        }
    }

    @PostMapping("/close/{orderNo}")
    @Operation(summary = "关闭支付订单")
    public ServerResponseEntity<Boolean> closeOrder(@PathVariable String orderNo, @RequestParam String payType) {
        try {
            PayService payService = "WECHAT".equals(payType) ? wechatPayService : alipayService;
            boolean result = payService.closeOrder(orderNo);
            return ServerResponseEntity.success(result);
        } catch (Exception e) {
            log.error("关闭支付订单失败", e);
            return ServerResponseEntity.fail("关闭支付订单失败: " + e.getMessage());
        }
    }

    @PostMapping("/refund/{orderNo}")
    @Operation(summary = "申请退款")
    public ServerResponseEntity<Boolean> refund(@PathVariable String orderNo,
                                              @RequestParam String payType,
                                              @RequestParam String refundReason) {
        try {
            PayService payService = "WECHAT".equals(payType) ? wechatPayService : alipayService;
            boolean result = payService.refund(orderNo, refundReason);
            return ServerResponseEntity.success(result);
        } catch (Exception e) {
            log.error("申请退款失败", e);
            return ServerResponseEntity.fail("申请退款失败: " + e.getMessage());
        }
    }
    
    /**
     * 解析微信支付通知数据
     * 实际项目中应使用SDK进行解析和验证
     */
    private Map<String, String> parseWechatNotifyData(String notifyData) {
        // 实际应使用SDK解析XML或JSON
        // 这里简化示例
        Map<String, String> params = new HashMap<>();
        params.put("out_trade_no", "订单号");
        params.put("transaction_id", "交易流水号");
        params.put("business_type", PayConstant.BusinessType.MEMBER_RECHARGE);
        return params;
    }
    
    /**
     * 从参数中获取业务类型
     */
    private String getBusinessTypeFromParams(Map<String, String> params) {
        // 实际应根据订单前缀或其他方式判断业务类型
        // 这里简化示例
        String orderNo = params.get("out_trade_no");
        if (orderNo != null && orderNo.startsWith("RC")) {
            return PayConstant.BusinessType.MEMBER_RECHARGE;
        }
        return PayConstant.BusinessType.GOODS_PURCHASE;
    }
    
    /**
     * 调用会员充值回调接口
     */
    private void callMemberRechargeCallback(String payType, Map<String, String> params) {
        // 实际项目中应使用Feign客户端或服务间调用
        // 这里简化示例
        log.info("调用会员充值回调处理: payType={}, params={}", payType, params);
        // 实际调用示例
        // String url = "http://localhost:8080/member/recharge/callback/" + payType;
        // restTemplate.postForEntity(url, params, ServerResponseEntity.class);
    }
} 